/**
 * 	MainWindow.java
 *
 *  This file is part of the PDFGen Syllabus Formatter Project.
 *  Copyright (C) 2011
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package org.dlsu.pdfgen.gui;

import java.io.File;
import java.io.IOException;

import javax.swing.*;

import org.dlsu.pdfgen.Controller;

/**
 * This class is the window for the file chooser dialog.
 * 
 * @author Kevin See
 * 
 */

public class MainWindow extends JFrame {
	// TODO: Add documentation for class attributes.

	private Controller controller;
	private JFileChooser fileChooser;

	private javax.swing.JMenuItem aboutMenuItem;
	private javax.swing.JMenuItem createXMLMenuItem;
	private javax.swing.JButton browseDestinationButton;
	private javax.swing.JButton browseSourceButton;
	private javax.swing.JTextField destinationField;
	private javax.swing.JMenuItem docuMenuItem;
	private javax.swing.JMenuItem exitMenuItem;
	private javax.swing.JButton generatePDFButton;
	private javax.swing.JButton jButton1;
	private javax.swing.JLabel jLabel2;
	private javax.swing.JLabel jLabel3;
	private javax.swing.JMenu jMenu1;
	private javax.swing.JMenu jMenu2;
	private javax.swing.JMenuBar jMenuBar1;
	private javax.swing.JPanel jPanel1;
	private javax.swing.JPanel jPanel2;
	private javax.swing.JTextField outputFileNameField;
	private javax.swing.JLabel outputFileNameLabel;
	private javax.swing.JButton previewButton;
	private javax.swing.JTextField sourceField;
	private javax.swing.JLabel syllabusFormatterLabel;
	private javax.swing.JComboBox templateComboBox;
	private javax.swing.JLabel templateLabel;

	/**
	 * The constructor.
	 * 
	 * @param Controller
	 *            The controller class for the window.
	 */
	public MainWindow(Controller controller) {
		initComponents();
		System.out.println("GUI started.");
		setVisible(true);
		setLocationRelativeTo(null);

		this.controller = controller;

		// Initialize fileChooser
		this.fileChooser = new JFileChooser();
		fileChooser.setFileFilter(new javax.swing.filechooser.FileFilter() {
			public String getDescription() {
				return "Extensible Markup Language (*.xml)";
			}

			@Override
			public boolean accept(File arg0) {
				if (arg0.getName().endsWith(".xml"))
					return true;
				else
					return false;
			}
		});
		fileChooser.setFileFilter(null);

		templateComboBox.setEnabled(false); // Set to 'true' if templates are
		// implemented (new 2011 syllabus
		// format).

		System.out.println("GUI displayed.");
	}

	/**
	 * 
	 * @param query
	 *            The question to be displayed to the user.
	 * @param title
	 *            The title of the JOptionDialogue.
	 * @return The response of the user (0 - Yes, 1 - No).
	 */
	public boolean queryUser(String query, String title) {
		int n = JOptionPane.showOptionDialog(this, query, title,
				JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null,
				new String[] { "Yes", "No" }, "Yes");

		if (n == 1) {
			return false;
		} else
			return true;
	}

	/**
	 * Displays a message to the user saying the operation was successful.
	 */
	public void displaySuccess() {
		JOptionPane.showMessageDialog(this, "Successfully generated PDF.",
				"Success", JOptionPane.INFORMATION_MESSAGE);
	}

	/**
	 * Displays a message to the user saying the operation was successful.
	 * 
	 * @param message
	 *            The optional message.
	 */
	public void displaySuccess(String message) {
		JOptionPane.showMessageDialog(this, message, "Success",
				JOptionPane.INFORMATION_MESSAGE);
	}

	/**
	 * Displays a message to the user saying the operation failed.
	 */
	public void displayError() {
		JOptionPane.showMessageDialog(this, "Failed to generate PDF.", "Error",
				JOptionPane.ERROR_MESSAGE);
	}

	/**
	 * 
	 * @return The file name of the intended output file.
	 */
	public String getFileName() {
		return outputFileNameField.getText();
	}

	/**
	 * Returns the directory of the source file.
	 * 
	 * @return String The directory of the source file.
	 */
	public String getSource() {
		return this.sourceField.getText();
	}

	/**
	 * Sets the value of the source field.
	 * 
	 * @param src
	 *            The String that will be displayed.
	 */
	public void setSource(String src) {
		this.sourceField.setText(src);
	}

	/**
	 * Returns the directory of where the user wants to place the output file.
	 * 
	 * @return
	 */
	public String getDestination() {
		return this.destinationField.getText();
	}

	/**
	 * Sets the value to the destination field.
	 * 
	 * @param dest
	 *            The String that will be displayed.
	 */
	public void setDestination(String dest) {
		this.destinationField.setText(dest);
	}

	/**
	 * Sets the fileChooser to FILES_ONLY selection mode.
	 */
	private void setToFileMode() {
		fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
	}

	/**
	 * Sets the fileChooser to DIRECTORIES_ONLY selection mode.
	 */
	private void setToDirectoryMode() {
		fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
	}

	/**
	 * Action to perform when the "About" in the menu bar is selected.
	 * 
	 * @param evt
	 */
	private void aboutMenuItemActionPerformed(java.awt.event.ActionEvent evt) {
		java.awt.EventQueue.invokeLater(new Runnable() {
			public void run() {
				new AboutWindow();
			}
		});
	}

	/**
	 * Action to perform when the "Documentation" in the menu bar is selected.
	 * 
	 * @param evt
	 */
	private void docuMenuItemActionPerformed(java.awt.event.ActionEvent evt) {
		// TODO add your handling code here:
	}

	/**
	 * Action to perform when the "Exit" menu item in the menu bar is selected
	 * 
	 * @param evt
	 */
	private void exitMenuItemActionPerformed(java.awt.event.ActionEvent evt) {
		controller.exitProgram();
	}
	
	/**
	 * Action to perform when the "Create New XML" menu item in the menu bar is selected
	 * 
	 * @param evt
	 */
	private void createXMLMenuItemActionPerformed(java.awt.event.ActionEvent evt) {
		new CreateXMLWindow();
	}

	/**
	 * Action to perform when the "Browse" button for the source is pressed.
	 * 
	 * @param evt
	 */
	private void browseSourceButtonActionPerformed(
			java.awt.event.ActionEvent evt) {
		setToFileMode();
		if (fileChooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
			if (fileChooser.getSelectedFile().getName().endsWith(".xml")) {
				System.out.println("Valid XML file.");
				sourceField.setText(fileChooser.getSelectedFile()
						.getAbsolutePath());
			} else {
				System.err.println("Not an XML file.");
				JOptionPane.showMessageDialog(this,
						"The file you selected was not an XML file.",
						"File Extension Mismatch", JOptionPane.ERROR_MESSAGE);
			}
		}
	}

	/**
	 * Action to perform when the "Browse" button for the destination is
	 * pressed.
	 * 
	 * @param evt
	 */
	private void browseDestinationButtonActionPerformed(
			java.awt.event.ActionEvent evt) {
		setToDirectoryMode();
		if (fileChooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
			destinationField.setText(fileChooser.getSelectedFile()
					.getAbsolutePath());

		}
	}

	/**
	 * Action to perform when the "Generate PDF" button is pressed.
	 * 
	 * @param evt
	 */
	private void generatePDFButtonActionPerformed(java.awt.event.ActionEvent evt) {
		if (!sourceField.getText().trim().isEmpty()
				&& !destinationField.getText().trim().isEmpty()) {
			File file = new File(destinationField.getText() + "\\"
					+ outputFileNameField.getText() + ".pdf");
			if (file.exists()) {
				int x = JOptionPane
						.showConfirmDialog(
								null,
								"File already exists! Do you want to overwrite the file?",
								"Overwrite File", JOptionPane.YES_NO_OPTION);
				if (x == 0)
					controller.generatePDF();
			} else
				controller.generatePDF();

		} else
			JOptionPane.showMessageDialog(this,
					"Please check source file and destination directory.",
					"Missing Fields", JOptionPane.ERROR_MESSAGE);
	}

	/**
	 * Action to perform when the "Preview" button is pressed.
	 * 
	 * @param evt
	 */
	private void previewButtonActionPerformed(java.awt.event.ActionEvent evt) {

		try {
			Controller.openPDF(controller.generateTempPDF());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * Initializes all components before launching window.
	 */
	private void initComponents() {

		jButton1 = new javax.swing.JButton();
		syllabusFormatterLabel = new javax.swing.JLabel();
		generatePDFButton = new javax.swing.JButton();
		jPanel1 = new javax.swing.JPanel();
		jLabel2 = new javax.swing.JLabel();
		browseSourceButton = new javax.swing.JButton();
		destinationField = new javax.swing.JTextField();
		sourceField = new javax.swing.JTextField();
		jLabel3 = new javax.swing.JLabel();
		browseDestinationButton = new javax.swing.JButton();
		jPanel2 = new javax.swing.JPanel();
		templateComboBox = new javax.swing.JComboBox();
		outputFileNameField = new javax.swing.JTextField();
		templateLabel = new javax.swing.JLabel();
		outputFileNameLabel = new javax.swing.JLabel();
		previewButton = new javax.swing.JButton();
		jMenuBar1 = new javax.swing.JMenuBar();
		jMenu1 = new javax.swing.JMenu();
		exitMenuItem = new javax.swing.JMenuItem();
		jMenu2 = new javax.swing.JMenu();
		docuMenuItem = new javax.swing.JMenuItem();
		aboutMenuItem = new javax.swing.JMenuItem();
		createXMLMenuItem = new javax.swing.JMenuItem();

		jButton1.setText("jButton1");

		setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
		setTitle("Syllabus Formatter");
		setMinimumSize(new java.awt.Dimension(502, 123));
		setResizable(false);

		syllabusFormatterLabel.setFont(new java.awt.Font("Tahoma", 1, 14));
		syllabusFormatterLabel.setText("Syllabus Formatter");

		generatePDFButton.setText("Generate PDF");
		generatePDFButton
				.addActionListener(new java.awt.event.ActionListener() {
					public void actionPerformed(java.awt.event.ActionEvent evt) {
						generatePDFButtonActionPerformed(evt);
					}
				});

		jPanel1.setBorder(javax.swing.BorderFactory
				.createTitledBorder("Directories"));

		jLabel2.setText("Source File (XML)");

		browseSourceButton.setText("Browse...");
		browseSourceButton
				.addActionListener(new java.awt.event.ActionListener() {
					public void actionPerformed(java.awt.event.ActionEvent evt) {
						browseSourceButtonActionPerformed(evt);
					}
				});

		jLabel3.setText("Destination");

		browseDestinationButton.setText("Browse...");
		browseDestinationButton
				.addActionListener(new java.awt.event.ActionListener() {
					public void actionPerformed(java.awt.event.ActionEvent evt) {
						browseDestinationButtonActionPerformed(evt);
					}
				});

		javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(
				jPanel1);
		jPanel1.setLayout(jPanel1Layout);
		jPanel1Layout
				.setHorizontalGroup(jPanel1Layout
						.createParallelGroup(
								javax.swing.GroupLayout.Alignment.LEADING)
						.addGroup(
								jPanel1Layout
										.createSequentialGroup()
										.addContainerGap()
										.addGroup(
												jPanel1Layout
														.createParallelGroup(
																javax.swing.GroupLayout.Alignment.TRAILING)
														.addComponent(jLabel3)
														.addComponent(jLabel2))
										.addPreferredGap(
												javax.swing.LayoutStyle.ComponentPlacement.RELATED)
										.addGroup(
												jPanel1Layout
														.createParallelGroup(
																javax.swing.GroupLayout.Alignment.LEADING)
														.addComponent(
																destinationField,
																javax.swing.GroupLayout.DEFAULT_SIZE,
																279,
																Short.MAX_VALUE)
														.addComponent(
																sourceField,
																javax.swing.GroupLayout.DEFAULT_SIZE,
																279,
																Short.MAX_VALUE))
										.addPreferredGap(
												javax.swing.LayoutStyle.ComponentPlacement.RELATED)
										.addGroup(
												jPanel1Layout
														.createParallelGroup(
																javax.swing.GroupLayout.Alignment.TRAILING)
														.addComponent(
																browseSourceButton)
														.addComponent(
																browseDestinationButton))
										.addContainerGap()));
		jPanel1Layout
				.setVerticalGroup(jPanel1Layout
						.createParallelGroup(
								javax.swing.GroupLayout.Alignment.LEADING)
						.addGroup(
								jPanel1Layout
										.createSequentialGroup()
										.addGroup(
												jPanel1Layout
														.createParallelGroup(
																javax.swing.GroupLayout.Alignment.BASELINE)
														.addComponent(jLabel2)
														.addComponent(
																sourceField,
																javax.swing.GroupLayout.PREFERRED_SIZE,
																javax.swing.GroupLayout.DEFAULT_SIZE,
																javax.swing.GroupLayout.PREFERRED_SIZE)
														.addComponent(
																browseSourceButton))
										.addPreferredGap(
												javax.swing.LayoutStyle.ComponentPlacement.RELATED)
										.addGroup(
												jPanel1Layout
														.createParallelGroup(
																javax.swing.GroupLayout.Alignment.BASELINE)
														.addComponent(jLabel3)
														.addComponent(
																destinationField,
																javax.swing.GroupLayout.PREFERRED_SIZE,
																javax.swing.GroupLayout.DEFAULT_SIZE,
																javax.swing.GroupLayout.PREFERRED_SIZE)
														.addComponent(
																browseDestinationButton))
										.addContainerGap(
												javax.swing.GroupLayout.DEFAULT_SIZE,
												Short.MAX_VALUE)));

		jPanel2.setBorder(javax.swing.BorderFactory
				.createTitledBorder("Output File"));

		templateLabel.setText("Template");

		outputFileNameLabel.setText("Output File Name");

		javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(
				jPanel2);
		jPanel2.setLayout(jPanel2Layout);
		jPanel2Layout
				.setHorizontalGroup(jPanel2Layout
						.createParallelGroup(
								javax.swing.GroupLayout.Alignment.LEADING)
						.addGroup(
								jPanel2Layout
										.createSequentialGroup()
										.addContainerGap()
										.addGroup(
												jPanel2Layout
														.createParallelGroup(
																javax.swing.GroupLayout.Alignment.TRAILING)
														.addComponent(
																templateLabel)
														.addComponent(
																outputFileNameLabel))
										.addPreferredGap(
												javax.swing.LayoutStyle.ComponentPlacement.RELATED)
										.addGroup(
												jPanel2Layout
														.createParallelGroup(
																javax.swing.GroupLayout.Alignment.LEADING)
														.addComponent(
																templateComboBox,
																javax.swing.GroupLayout.PREFERRED_SIZE,
																162,
																javax.swing.GroupLayout.PREFERRED_SIZE)
														.addComponent(
																outputFileNameField,
																javax.swing.GroupLayout.PREFERRED_SIZE,
																275,
																javax.swing.GroupLayout.PREFERRED_SIZE))
										.addContainerGap(98, Short.MAX_VALUE)));
		jPanel2Layout
				.setVerticalGroup(jPanel2Layout
						.createParallelGroup(
								javax.swing.GroupLayout.Alignment.LEADING)
						.addGroup(
								jPanel2Layout
										.createSequentialGroup()
										.addGroup(
												jPanel2Layout
														.createParallelGroup(
																javax.swing.GroupLayout.Alignment.BASELINE)
														.addComponent(
																templateLabel)
														.addComponent(
																templateComboBox,
																javax.swing.GroupLayout.PREFERRED_SIZE,
																javax.swing.GroupLayout.DEFAULT_SIZE,
																javax.swing.GroupLayout.PREFERRED_SIZE))
										.addPreferredGap(
												javax.swing.LayoutStyle.ComponentPlacement.RELATED)
										.addGroup(
												jPanel2Layout
														.createParallelGroup(
																javax.swing.GroupLayout.Alignment.BASELINE)
														.addComponent(
																outputFileNameField,
																javax.swing.GroupLayout.PREFERRED_SIZE,
																javax.swing.GroupLayout.DEFAULT_SIZE,
																javax.swing.GroupLayout.PREFERRED_SIZE)
														.addComponent(
																outputFileNameLabel))
										.addContainerGap(
												javax.swing.GroupLayout.DEFAULT_SIZE,
												Short.MAX_VALUE)));

		previewButton.setText("Preview");
		previewButton.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				previewButtonActionPerformed(evt);
			}
		});

		jMenu1.setText("Options");

		createXMLMenuItem.setText("Create New XML");
		createXMLMenuItem.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				createXMLMenuItemActionPerformed(evt);
			}
		});
		jMenu1.add(createXMLMenuItem);
		
		exitMenuItem.setText("Exit");
		exitMenuItem.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				exitMenuItemActionPerformed(evt);
			}
		});
		jMenu1.add(exitMenuItem);

		jMenuBar1.add(jMenu1);

		jMenu2.setText("Help");

		docuMenuItem.setText("Documentation");
		docuMenuItem.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				docuMenuItemActionPerformed(evt);
			}
		});
		jMenu2.add(docuMenuItem);

		aboutMenuItem.setText("About");
		aboutMenuItem.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				aboutMenuItemActionPerformed(evt);
			}
		});
		jMenu2.add(aboutMenuItem);

		jMenuBar1.add(jMenu2);

		setJMenuBar(jMenuBar1);

		javax.swing.GroupLayout layout = new javax.swing.GroupLayout(
				getContentPane());
		getContentPane().setLayout(layout);
		layout.setHorizontalGroup(layout
				.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
				.addGroup(
						layout.createSequentialGroup()
								.addContainerGap()
								.addGroup(
										layout.createParallelGroup(
												javax.swing.GroupLayout.Alignment.LEADING)
												.addGroup(
														layout.createParallelGroup(
																javax.swing.GroupLayout.Alignment.LEADING)
																.addGroup(
																		layout.createSequentialGroup()
																				.addComponent(
																						syllabusFormatterLabel)
																				.addGap(362,
																						362,
																						362))
																.addGroup(
																		layout.createSequentialGroup()
																				.addComponent(
																						jPanel1,
																						javax.swing.GroupLayout.DEFAULT_SIZE,
																						javax.swing.GroupLayout.DEFAULT_SIZE,
																						Short.MAX_VALUE)
																				.addContainerGap())
																.addGroup(
																		layout.createSequentialGroup()
																				.addComponent(
																						jPanel2,
																						javax.swing.GroupLayout.DEFAULT_SIZE,
																						javax.swing.GroupLayout.DEFAULT_SIZE,
																						Short.MAX_VALUE)
																				.addContainerGap()))
												.addGroup(
														javax.swing.GroupLayout.Alignment.TRAILING,
														layout.createSequentialGroup()
																.addComponent(
																		previewButton)
																.addPreferredGap(
																		javax.swing.LayoutStyle.ComponentPlacement.RELATED)
																.addComponent(
																		generatePDFButton)
																.addContainerGap()))));
		layout.setVerticalGroup(layout
				.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
				.addGroup(
						layout.createSequentialGroup()
								.addContainerGap()
								.addComponent(syllabusFormatterLabel)
								.addPreferredGap(
										javax.swing.LayoutStyle.ComponentPlacement.RELATED)
								.addComponent(jPanel1,
										javax.swing.GroupLayout.PREFERRED_SIZE,
										javax.swing.GroupLayout.DEFAULT_SIZE,
										javax.swing.GroupLayout.PREFERRED_SIZE)
								.addPreferredGap(
										javax.swing.LayoutStyle.ComponentPlacement.RELATED)
								.addComponent(jPanel2,
										javax.swing.GroupLayout.PREFERRED_SIZE,
										javax.swing.GroupLayout.DEFAULT_SIZE,
										javax.swing.GroupLayout.PREFERRED_SIZE)
								.addPreferredGap(
										javax.swing.LayoutStyle.ComponentPlacement.RELATED)
								.addGroup(
										layout.createParallelGroup(
												javax.swing.GroupLayout.Alignment.BASELINE)
												.addComponent(generatePDFButton)
												.addComponent(previewButton))
								.addContainerGap(
										javax.swing.GroupLayout.DEFAULT_SIZE,
										Short.MAX_VALUE)));

		pack();
	}

}
